<?php

namespace app\common\model;

use app\common\pluings\service\Oss;
use app\common\traits\GetBase;
use app\common\utils\UtilsLog;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * Class User
 * @package app\model
 */
class User extends ModelBase
{
    use SoftDelete;
    // 默认不查询出来的字段
    protected $hidden = ['password','wxopenid','wxunionid','delete_time'];
    // 验证器
    protected $validate = \app\common\validate\User::class;
    // json 字段定义
    protected $json = ['avator'];
    // 只读字段
    protected $readonly = ['id','uuid','create_time','creator'];

    /**
     * 新增
     */
    public function add($data,$userId){
        empty($data['uuid']) && $data['uuid'] = uuid();
        $data['creator'] = $userId;
        $data['updater'] = $userId;
        validate($this->validate)->scene('add')->check($data);

        !empty($data['password']) && $data['password'] = password_hash($data['password'],1);

        $data = $this->createda($data);
        // json字段自动赋值
        empty($data['avator']) && $data['avator']=[];

        return User::create($data);
    }

    /**
     * 修改用户
     */
    public function edit($data,$userId){
        $data['updater'] = $userId;
        // 不支持直接修改密码
        unset($data['password']);
        validate($this->validate)->scene('edit')->check($data);
        $data['id'] === 1 && exception('无操作权限');

        $user = User::update($data,['id'=>$data['id'],'uuid'=>$data['uuid']]);
        return $user;
    }

    /**
     * 修改密码
     */
    public function editPassword($data){
        validate($this->validate)->scene('edit-password')->check($data);
        if(!empty($data['password'])){
            $data['password'] = password_hash($data['password'],1);
        }
        $data['id'] === 1 && exception('无操作权限');
        $updateData = [
            'id'=>$data['id'],
            'uuid'=>$data['uuid'],
            'password'=>$data['password']
        ];

        $user = User::update($updateData,['id'=>$updateData['id'],'uuid'=>$updateData['uuid']]);
        return $user;
    }

    /**
     * @param $data
     * @param $userId
     * @return bool
     * 删除
     */
    public function del($data, $userId)
    {
        validate($this->validate)->scene('del')->check($data);
        $data['id'] === 1 && exception('无操作权限');
        $delFlag = false;
        Db::startTrans();
        try {
            // 先更新再删除
            User::where('id',  $data['id'])
                ->where('uuid', $data['uuid'])
                ->save(['updater' => $userId]);

            $delFlag = User::where(['id'=>$data['id'],'uuid'=>$data['uuid']])->find()->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            exception('删除失败');
        }

        return $delFlag;
    }

    /**
     * 用户角色一对一
     */
    public function role()
    {
        return $this->hasOne(UserRole::class,'uid','id');
    }

    /**
     * 获取用户权限
     */
    public function getAuthoritiesAttr(){
        $authorities = [];

        if($this['id'] == 1){
            return ['admin'];
        }

        if(!empty($this['role']) && !empty($this['role']['roles'])){
            $roles = $this['role']['roles'];
            foreach ($roles as $item){
                $roleInfo = app(Role::class,[])->findByCache($item);
                if(!empty($roleInfo)){
                    $roleInfo = json_decode(json_encode($roleInfo),true);
                    $authorities = array_merge($authorities,$roleInfo['rules']);
                }
            }
        }
        return $authorities;
    }

    /**
     * 头像设置器
     */
    public function setAvatorAttr($value){
        $result = [];
        if(!empty($value)){
            foreach ($value as $item){
                array_push($result,[
                    'originName'=>empty($item['originName'])?'':$item['originName'],
                    'path'=>empty($item['path'])?'':$item['path'],
                    'uname'=>empty($item['uname'])?'':$item['uname']
                ]);
            }
        }
        return $result;
    }

    /**
     * 头像设置器
     */
    public function getAvatorAttr($value){
        if(!empty($value)){
            $value = (array)$value;
            foreach ($value as $key=>$item){
                $value[$key]['url'] = $item['path'];
            }
        }
        return $value;
    }
}
